#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
抓取 B 站各榜单，写入 data/00001、00002…（递增目录），并维护 data/cumulative/ 累计文件。
"""

from datetime import datetime
import pandas as pd
import requests

from .config import HEADERS, URLS
from . import save as saver

def fetch_category(category: str, url: str) -> pd.DataFrame:
    r = requests.get(url, headers=HEADERS, timeout=15)
    r.raise_for_status()
    data_list = r.json()["data"]["list"]

    rows = []
    now_iso = datetime.now().isoformat(timespec="seconds")
    for d in data_list:
        bvid = d.get("bvid", "")
        rows.append({
            "bvid": bvid,
            "视频标题": d.get("title", ""),
            "视频地址": f"https://www.bilibili.com/video/{bvid}" if bvid else "",
            "作者": d.get("owner", {}).get("name", ""),
            "播放数": d.get("stat", {}).get("view", 0),
            "弹幕数": d.get("stat", {}).get("danmaku", 0),
            "投币数": d.get("stat", {}).get("coin", 0),
            "点赞数": d.get("stat", {}).get("like", 0),
            "分享数": d.get("stat", {}).get("share", 0),
            "收藏数": d.get("stat", {}).get("favorite", 0),
            "抓取时间": now_iso,
        })
    return pd.DataFrame(rows)

def run_once() -> None:
    run_dir = saver.make_run_dir(digits=5)  # 00001 起
    print(f"[RUN] 输出目录: {run_dir}")

    manifest_items = []
    for category, url in URLS.items():
        try:
            df = fetch_category(category, url)
            single_path = saver.write_category_csv(df, category, run_dir)
            added, total, cum_path = saver.incremental_update(category, df)

            info = {
                "category": category,
                "http": 200,
                "written": str(single_path),
                "cumulative": str(cum_path),
                "added_new": added,
                "cumulative_total": total,
                "rows_this_run": len(df),
            }
            manifest_items.append(info)

            print(
                f"[OK] {category}: 本次 {len(df)} 条, 递增新增 {added} 条, 累计 {total} 条\n"
                f"     本次文件: {single_path}\n"
                f"     累计文件: {cum_path}"
            )
        except Exception as e:
            manifest_items.append({"category": category, "error": str(e)})
            print(f"[ERR] {category}: {e}")

    saver.write_manifest(run_dir, manifest_items)
    print(f"[DONE] Manifest: {run_dir/'manifest.json'}")
